package cn.wolfcode.p2p.base.service.impl;

import cn.wolfcode.p2p.base.exception.DisplayableException;
import cn.wolfcode.p2p.base.service.IVerifyCodeService;
import cn.wolfcode.p2p.base.util.Constants;
import cn.wolfcode.p2p.base.util.DateUtil;
import cn.wolfcode.p2p.base.util.UserContext;
import cn.wolfcode.p2p.base.vo.VerifyCodeVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StreamUtils;

import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.UUID;

@Service@Transactional
public class VerifyCodeServiceImpl implements IVerifyCodeService {

    @Override
    public void sendVerifyCode(String phoneNumber) {
        //校验上一次发送的时间和当前时间的间隔是否超过了90s
        VerifyCodeVo vo = UserContext.getVerifyCodeVO();
        if (vo == null || DateUtil.getBetweenTime(vo.getSendTime(), new Date()) > Constants.VERIFYCODE_INTERVAL_TIME) {
            //生成随机验证码
            String randomCode = UUID.randomUUID().toString().substring(0, 4);
            //执行短信的发送
            StringBuilder msg = new StringBuilder();
            msg.append("欢迎注册p2p,手机验证码为:").append(randomCode).
                    append(",请尽快填写,有效期为").append(Constants.VERIFYCODE_VALID_TIME).append("分钟");
            System.out.println(msg.toString()); //模拟发送
            try {
//                sendRealSms(phoneNumber, msg.toString());
                System.out.println(msg.toString());
                vo = new VerifyCodeVo();
                vo.setPhoneNumber(phoneNumber);
                vo.setRandomCode(randomCode);
                vo.setSendTime(new Date());
                UserContext.setVerifyCodeVo(vo);
            } catch (Exception e) {
                throw new DisplayableException(e.getMessage());
            }
        } else {
            throw new DisplayableException("发送太频繁,请稍后再试");
        }
    }

    //http://utf8.api.smschinese.cn/?Uid=本站用户名&Key=接口安全秘钥&smsMob=手机号码&smsText=验证码:8888
    private void sendRealSms(String phoneNumber, String msg) throws Exception {
        //定义请求的地址
        URL url = new URL("http://utf8.api.smschinese.cn");
        //建立连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //给连接配置参数
        conn.setRequestMethod("GET");
        conn.setDoOutput(true); //往对方的服务器发送数据
        //拼接需要发送的数据
        StringBuilder sb = new StringBuilder(50);
        sb.append("Uid=").append("wuyiqun").append("&Key=").append("d41d8cd98f00b204e980")
                .append("&smsMob=").append(phoneNumber).append("&smsText=").append(msg);
        //输出内容
        conn.getOutputStream().write(sb.toString().getBytes("utf-8"));
        //发送请求
        conn.connect();
        //获取响应的数据
        String respStr = StreamUtils.copyToString(conn.getInputStream(), Charset.forName("utf-8"));
        int respCode = Integer.parseInt(respStr);
        System.out.println(respCode);
        if (respCode < 0) {
            throw new DisplayableException("短信发送失败,请联系管理员");
        }

    }
}
